$(function () {
  // 登录框与注册框的互斥渲染
  $('#goto-register').on('click', () => {
    $('#register').stop().show()
  })

  $('#goto-login').on('click', () => {
    $('#register').stop().hide()
  })

  // 注册事件
  $('#register .layui-form').on('submit', async e => {
    e.preventDefault()
    const data = {
      username: $('#register input[name=username]').val(),
      password: $('#register input[name=password]').val(),
    }
    // 处理请求要用的数据
    const dataStr = handleDataFormat(data)
    // 注册请求
    const res = await reqRegisterPost(dataStr)
    console.log(res)
    const { status, message } = res
    if (status === 0) {
      layer.msg(message, { time: 1500, icon: 1 })
      $('#register').stop().hide(300)
    } else {
      layer.msg(message, { time: 2000, icon: 2 })
    }
  })

  $('#login .layui-form').on('submit', async e => {
    e.preventDefault()
    const data = {
      username: $('#login input[name=username]').val(),
      password: $('#login input[name=password]').val(),
    }
    // 处理请求要用的数据
    const dataStr = handleDataFormat(data)
    // 登录请求
    const res = await reqLoginPost(dataStr)
    console.log(res)
    const { status, message } = res
    if (status === 0) {
      layer.msg(message, { time: 1500, icon: 1 })
      // 本地存储token
      sessionStorage.setItem('bigEventToken', res.token)
      location.href = 'index.html'
    } else {
      layer.msg(message + '账号或者密码不正确', { time: 2000, icon: 2 })
    }
  })
})
